// pages/business/add-goods/add-goods.js
var app = getApp();
import upload from '../../../utils/upload'
let richText = null;  //富文本编辑器实例
// 语言
var util = require('../../../utils/util.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isShowPopup:true,
    title:"添加商品",  // 编辑商品
    prices:[{qty:null,price:null}],
    pictures:[],
    lists:[],
    is_live:false, // 是否设为直播商品
    goodsDetail:"",//商品详情

    image_main:"", // 商品主图
    activeSelect:'',
    goodsType:{
      "社交电商自营":1,
      "社区团购自营":2,
      "天天精选商品库":3
    },
    goodsTypeRever:{
      1:"社交电商自营",
      2:"社区团购自营",
      3:"天天精选商品库"
    },
    disabled:false,
    template:[],
    templateObj:{},
    category:[[],[],[]],
    categoryId:[[],[],[]],
    categoryName:[[],[],[]],
  },
  // switch更改状态
  is_liveChange(e){
    if(this.data.disabled){
      return;
    }
    this.setData({
      is_live:e.detail.value
    })
  },

  // 上传图片
  upShopLogo(){
    if(this.data.disabled){
      return;
    }
    upload.upShopLogo((res)=>{
      this.setData({
        image_main:res.data.url
      })
    },"/product/upload")
  },
  upShopContent(){
    if(this.data.disabled){
      return;
    }
    upload.upShopLogo((res)=>{
      var pictures = this.data.pictures;
      pictures.push(res.data.url)
      this.setData({
        pictures:pictures
      })
    },"/product/upload")
  },
  // 增加
  add(){
    if(this.data.disabled){
      return;
    }
    let prices=this.data.prices
    prices.push({qty:null,price:null})
    this.setData({
      prices:prices
    })
  },
  // 减少
  reduce(e){
    if(this.data.disabled){
      return;
    }
  // 删除某一项
    let prices=this.data.prices
    prices.splice(e.currentTarget.dataset.index,1)
    this.setData({
      prices:prices
    })
  },
  // 确认添加
  confrim(){
    let that=this,customer_id = wx.getStorageSync('customer_id'),tem=this.data.templateObj[this.data.price_template];
    wx.request({
      url: app.globalData.urls +( this.data.id?'/product/product-update': '/product/product-add'),
      header: app.getRequestHeader(),
      method:"POST",
      data: {
        ...(this.data.id?{product_id:this.data.id}:{}),
        user_id:customer_id.customer_id,
        bdmin_user_id:util.getBdmin_user_id(),
        image_main:this.data.image_main, // 商品主图url
        goods_type:this.data.goodsType[this.data.goods_type], // 商品类型 1社交电商自营 2社区团购自营 3天天精选商品库（3不可被选泽）
        goods_name:this.data.goods_name,
        category_id:this.data.categoryId[2][this.data.c3],
        lable_description:this.data.lable_description1+","+this.data.lable_description2+","+this.data.lable_description3,
        price_template:tem &&tem.id||'',
        cost_price:this.data.cost_price,
        price:this.data.price,
        show_price:this.data.show_price,
        tier_price:JSON.stringify(this.data.prices),
        is_live:this.data.is_live,
        live_name:this.data.live_name,//直播商品标题，直播必填,最多14个字
        qty:this.data.qty,
        description:this.data.description,
        image_description:this.data.pictures.join(','),
        new_value:this.data.new_value,
        hot_value:this.data.hot_value
      },
      success: function (res) {
        if (res.data.code == 200) {
          wx.navigateBack({
            delta: 1,
          })
        }else{
          wx.showToast({
            title: res.data.message,
            icon:'none'
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.priceTemplate();
    this.getCategory(0);

    if(options.id){
      wx.showLoading()
      this.setData({
        id:options.id
      })
      setTimeout(()=>{
        this.getDetail(options.id)
      },1000)
    }
  },
  // 编辑详情
  getDetail(id){
    var that = this,customer_id = wx.getStorageSync('customer_id');
    wx.request({
      url: app.globalData.urls + '/product/product-detail',
      method: 'GET',
      data: {
        bdmin_user_id:util.getBdmin_user_id(),
        product_id:id
      },
      header: app.getPostRequestHeader(),
      success: function (res) {
        if(res.data.code==200){
          let data =  res.data.data;
          console.log("编辑",data)
          that.getCategory(1,data.category_one)
          that.getCategory(2,data.category_two)

          for(let i in data){
            that.setData({
              [i]:data[i]
            })
          }

          let des=data.lable_description && data.lable_description.split(',') || [],
          tem=that.data.templateObjId[data.price_template];
          console.log("价格模板",tem,data.price_template,that.data.templateObjId)
          that.setData({
            prices:JSON.parse(data.tier_price),
            pictures:data.image_description.split(','),
            price_template:tem && tem.name || '',
            lable_description1:des[0]||'',
            lable_description2:des[1]||'',
            lable_description3:des[2]||'',
            goods_type:that.data.goodsTypeRever[data.goods_type],
            c1:that.data.categoryName[0][data.category_one],
            disabled:data.user_id != customer_id.customer_id
          })
          setTimeout(()=>{
            wx.hideLoading()
            that.setData({
              c3:that.data.categoryName[2][data.category_three],
              c2:that.data.categoryName[1][data.category_two]
            })
          },2000)

        }else{
          wx.showToast({
            title: res.data.message,
            icon:'none'
          })
        }
      }
    })
  },
  // 商品分类
  getCategory(type,parent_id){
    var that = this;
    wx.request({
      url: app.globalData.urls + '/product/category',
      method: 'GET',
      data: {
        bdmin_user_id:util.getBdmin_user_id(),
        parent_id:parent_id
      },
      header: app.getPostRequestHeader(),
      success: function (res) {
        if(res.data.code==200){
          let data = res.data.data,dataId={},dataArr=[],dataName={};
          dataArr = data.map(val=>{
            dataId[val.name] = val.id;
            dataName[val.id] = val.name;
            return val.name;
          })
          that.setData({
            ["categoryId["+type+"]"]:dataId,
            ["category["+type+"]"]:dataArr,
            ["categoryName["+type+"]"]:dataName,
          })
        }
      }
    })
  },
  // 价格模板
  priceTemplate(){
    var that = this;
    wx.request({
      url: app.globalData.urls + '/product/price-template',
      method: 'GET',
      data: {
        bdmin_user_id:util.getBdmin_user_id()
      },
      header: app.getPostRequestHeader(),
      success: function (res) {
        if(res.data.code==200){
          let data = res.data.data;
          that.setData({
            template:data.map(val=>val.name),
            templateObj:data.reduce((prev,val)=>{
              prev[val.name] = val;
              return prev
            },{}),
            templateObjId:data.reduce((prev,val)=>{
              prev[val.id] = val;
              return prev
            },{})
          })
        }
      }
    })
  },
  // input框失去焦点
  blurChange(e){
    let type = e.currentTarget.dataset.type
    if(type=="tier_price"){
      let item=e.currentTarget.dataset,price = this.data.prices;
      price[item.i][item.p] = e.detail.value
      this.setData({
        prices:price
      })
    }else{
      this.setData({
        [type]:e.detail.value
      })
    }
  },
  // select框选中的
  selected(e){
    let getP=e.detail

    this.setData({
      [this.data.activeSelect]: getP
    })

    if(this.data.activeSelect=="c1"||this.data.activeSelect=="c2"){
      let index = this.data.activeSelect=="c1" ? 0 :1;
      this.getCategory(index+1,this.data.categoryId[index][getP])
    }

    if(this.data.activeSelect == 'price_template'){
      let getT=this.data.templateObj[getP];

      let price=Number(this.data.cost_price) + Number((Number(getT.price_rto)/100)*this.data.cost_price)
      this.setData({
        price:price.toFixed(2) , // 拼团价
        show_price:(price + (Number(getT.show_price_rto)/100)*price).toFixed(2) //划线价
      })
      // 拼团价等于  成本价*(100+price_rto)/100
      // 划线价等于  拼团价*（100+show_price_rto）/100
    }
  },
  // 模拟 select 框回调
  select(e){
    let type=e.currentTarget.dataset.type;
    console.log(type,'-----',this.data.goods_name)
    if(this.data.disabled && (type!="price_template" && this.data.goods_name!='天天精选商品库')){
      return;
    }
    if(type=="goods_type"){ // 商品类型
      this.setData({
        lists:["社交电商自营","社区团购自营"],
        title:"商品类型"
      })
    }
    if(type=="price_template"){ // 价格模板
      this.setData({
        lists:this.data.template,
        title:"价格模板"
      })
    }
    if(type=="c1" || type=="c2" || type=="c3" ){
      this.setData({
        lists:this.data.category[e.currentTarget.dataset.index],
        title:"所属类目"
      })
    }
    this.setData({
      activeSelect:type,
      isShowPopup:false
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /**
   * 富文本编辑器
   */
  //清空编辑器事件
  // clearBeforeEvent(){
  //   console.log('[clearBeforeEvent callback]')
  //   wx.showModal({
  //     cancelText: '取消',
  //     confirmText: '确认',
  //     content: '确认清空编辑器内容吗？',
  //     success: (result) => {
  //       if(result.confirm){
  //         richText.clear();
  //       }
  //     },
  //     fail: (res) => {},
  //   })
  // },
  //  //清空编辑器成功回调
  //  clearSuccess(){
  //   console.log('[clearSuccess callback]')
  // },
  //  //撤销
  //  undo() {
  //   console.log('[undo callback]')
  // },

  // //恢复
  // restore() {
  //   console.log('[restore callback]')
  // },

  //清空编辑器内容
  // clear() {
  //   this.editorCtx.clear({
  //     success: res => {
  //       console.log("[clear success]", res)
  //     }
  //   })
  // },
  // 编辑器初始化完成时触发，可以获取组件实例
  // onEditorReady() {
  //   richText = this.selectComponent('#richText'); //获取组件实例
  //   console.log('[onEditorReady callback]')
  // },
  //编辑器聚焦时触发
  // bindfocus(res) {
  //   let {
  //     value
  //   } = res.detail;
  //   console.log('[bindfocus callback]=>', value)
  // },

  //编辑器失去焦点时触发
  // bindblur(res) {
  //   let {
  //     value
  //   } = res.detail;
  //   // 主要是这个事件 goodsDetail
  //   console.log('[bindblur callback]=>', value)
  // },

  //编辑器输入中时触发
  // bindinput(res) {
  //   let {
  //     value
  //   } = res.detail;
  //   this.data.richTextContents = value.detail.html;
  // },
 //插入图片
  // insertImageEvent() {
  //   wx.chooseImage({
  //     count: 1,
  //     success: res => {
  //       let path = res.tempFilePaths[0];
  //       console.log("查看上传",richText)
  //       //调用子组件方法，图片应先上传再插入，不然预览时无法查看图片。
  //       richText.insertImageMethod(path).then(res => {
  //         console.log('[insert image success callback]=>', res)
  //       }).catch(res => {
  //         console.log('[insert image fail callback]=>', res)
  //       });
  //     }
  //   })
  // },
 //保存，获取编辑器内容
  // getEditorContent(res) {
  //   let {
  //     value
  //   } = res.detail;
  //   wx.showToast({
  //     title: '获取编辑器内容成功',
  //     icon: 'none',
  //   })
  //   console.log('[getEditorContent callback]=>', value)
  // },



})
